/*
 * @Author: Ryan Huang
 * @Description:
 * @Date: 2019-04-04 18:30:06
 */
package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"my/homework/chatroom/model"
	"net"
	"os"
	"time"
)

type Header struct {
	Addr  string `json:"addr"`
	Name  string `json:"name"`
	Index int    `json:"index"`
	Time  int    `json:time`
}

type Body struct {
	Content string `json:"content"`
}

type Msg struct {
	Header
	Body
}

func main() {
	var msgIndex int = 0
	inputReader := bufio.NewReader(os.Stdin)
	remoteAddr, _ := net.ResolveUDPAddr("udp", model.ServerAddr)
	conn, _ := net.DialUDP("udp", nil, remoteAddr)
	fmt.Println("请输入你在聊天室的名字：")
	buffer := make([]byte, 4096)
	buffer, _, _ = inputReader.ReadLine()
	name := string(buffer)
	fmt.Println("欢迎 " + name + " 进入聊天室........")
	fmt.Println()
	msgIndex++
	go receiveMsg(conn)
	laddr := conn.LocalAddr()
	for {
		buffer = make([]byte, 4096)
		buffer, _, _ = inputReader.ReadLine()
		msgHeader := model.Header{laddr.String(), name, msgIndex, int(time.Now().Unix())}
		msgBody := model.Body{string(buffer)}
		msg := model.Msg{msgHeader, msgBody}
		msgJson, _ := json.Marshal(msg)
		//conn已经Dial，确定了对方地址，所以不能用 WriteToUDP
		_, sendErr := conn.Write(msgJson)
		if sendErr != nil {
			fmt.Println("客户端提示：您的消息未发送成功！！！")
		}
		msgIndex++
	}
}

func receiveMsg(conn *net.UDPConn) {
	for {
		buffer := make([]byte, 4096)
		n, _ := conn.Read(buffer)
		var jsonMsg model.Msg
		json.Unmarshal(buffer[:n], &jsonMsg)
		content := jsonMsg.Body.Content
		name := jsonMsg.Header.Name
		timeFormat := time.Unix(int64(jsonMsg.Header.Time), 0).Format("15:04:05")
		msg := name + " : " + content + "            ------" + timeFormat
		fmt.Println(msg)
	}
}
